<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="queryParams.username" placeholder="用户名" clearable @keyup.enter="handleQuery()"
            :disabled="userStore.judgeGuestUser()" />
        </el-form-item>
        <el-form-item label="联系方式" prop="mobile">
          <el-input v-model="queryParams.mobile" placeholder="联系方式" clearable @keyup.enter="handleQuery()" />
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="queryParams.status" multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="3"
            placeholder="请选择" style="width: 270px">
            <el-option v-for="item in OrderStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['sys:order:add']" type="success" @click="handleOpenDialog(undefined, 'add')">
          <template #icon>
            <Plus />
          </template>
          新增
        </el-button>
        <el-button v-hasPerm="['sys:order:delete']" type="danger" :disabled="removeIds.length === 0"
          @click="handleDelete()">
          <template #icon>
            <Delete />
          </template>
          删除
        </el-button>
      </div>

      <el-table ref="dataTableRef" v-loading="loading" :data="pageData" highlight-current-row border
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="username" label="用户名" prop="username" min-width="150" align="center" />
        <el-table-column key="mobile" label="联系方式" prop="mobile" min-width="150" align="center" />
        <el-table-column label="商品列表" min-width="150" align="center">
          <template #default="scope">
            <el-link type="primary" @click="viewProductDialog(scope.row.id)">{{ scope.row.productQuantity }}件</el-link>
          </template>
        </el-table-column>
        <el-table-column key="courierName" label="配送人员" prop="courierName" min-width="150" align="center" />
        <el-table-column key="status" label="订单状态" prop="status" min-width="150" align="center">
          <template #default="scope">
            <el-tag :type="OrderStatusOptions.find((item) => item.value === scope.row.status)?.type">{{
              OrderStatusOptions.find((item) => item.value === scope.row.status)?.label}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="地址" align="center" min-width="400">
          <template #default="scope">
            {{ scope.row.province }} {{ scope.row.city }} {{ scope.row.country }}{{ scope.row.address }}
          </template>
        </el-table-column>
        <el-table-column key="totalPoints" label="花费的积分" prop="totalPoints" min-width="150" align="center" sortable />

        <el-table-column fixed="right" label="操作" width="220" align="center">
          <template #default="scope">
            <el-button v-hasPerm="['sys:order:edit']" type="primary" size="small" link
              @click="handleOpenDialog(scope.row.id, 'edit')">
              <template #icon>
                <Edit />
              </template>
              编辑
            </el-button>
            <el-button v-hasPerm="['sys:order:delete']" type="danger" size="small" link
              @click="handleDelete(scope.row.id)">
              <template #icon>
                <Delete />
              </template>
              删除
            </el-button>
            <!--发货-->
            <el-button type="primary" size="small" link
              v-if="scope.row.status == OrderStatusOptions.find(item => item.label == '已支付')?.value && userStore.judgeOrgUser()"
              @click="handleOpenDialog(scope.row.id, 'deliver')">发货</el-button>
            <!--结算支付-->
            <el-popconfirm title="确认要支付吗？" @confirm="settleOrder(scope.row.id)">
              <template #reference>
                <el-button type="primary" size="small" link
                  v-if="scope.row.status == OrderStatusOptions.find(item => item.label == '未支付')?.value && userStore.judgeGuestUser()">支付</el-button>
              </template>
            </el-popconfirm>

            <!--确认收货-->
            <el-popconfirm title="确认要确认收货吗？" @confirm="confirmReceipt(scope.row.id)">
              <template #reference>
                <el-button type="primary" size="small" link
                  v-if="scope.row.status == OrderStatusOptions.find(item => item.label == '已发货')?.value && userStore.judgeGuestUser()">确认收货</el-button>
              </template>
            </el-popconfirm>
            <!--取消订单-->
            <el-popconfirm title="确认要取消订单吗？" @confirm="cancelOrder(scope.row.id)">
              <template #reference>
                <el-button type="primary" size="small" link v-if="scope.row.status == OrderStatusOptions.find(item => item.label == '未支付')?.value
                  && userStore.judgeNormalUser()">取消订单</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery()" />
    </el-card>

    <!-- 订单管理表单弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="700px" @close="handleCloseDialog()">
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px" style="padding:0 20px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="用户名" :disabled="dialog.type == 'deliver'" />
        </el-form-item>

        <el-form-item label="联系方式" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="联系方式" :disabled="dialog.type == 'deliver'" />
        </el-form-item>

        <el-form-item label="订单状态" prop="status">
          <el-select v-model="formData.status" style="width:150px" :disabled="dialog.type == 'deliver'">
            <el-option v-for="item in OrderStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <div style="display:flex">
            <el-cascader size="large" :options="pcaTextArr" v-model="formData.area" style="width:350px"
              :disabled="dialog.type == 'deliver'"></el-cascader>
            <el-input v-model="formData.address" placeholder="详细地址" :disabled="dialog.type == 'deliver'" />
          </div>
        </el-form-item>
        <el-form-item label="花费的积分" prop="totalPoints">
          <el-input v-model="formData.totalPoints" placeholder="花费的积分" :disabled="dialog.type == 'deliver'" />
        </el-form-item>
        <el-form-item label="配送人员" prop="courierId" v-if="userStore.judgeOrgUser()">
          <el-select v-model="formData.courierId" placeholder="请选择" style="width:150px">
            <el-option v-for="(item, index) in courierOptions" :key="item.userId" :value="item.userId"
              :label="item.username"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseDialog()">取消</el-button>
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 商品列表抽屉-->
    <el-drawer v-model="productDrawer.visible" :title="productDrawer.title" @close="closeProductDrawer()">
      <el-space v-for="product in productDrawer.productList" :key="product.productId">
        <!-- 图片预览 -->
        <el-card style="
        width: 100%;
        border: #a9a9a9 1px solid;
        border-radius: 5px;
        margin: 5px;
        display: flex;
      ">
          <el-image :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[product.pic]"
            style="width: 150px; height: 100px" :src="product.pic" fit="cover" />
          <div style="margin-left: 10px;width:100%;">
            <p>名称：{{ product.productName }}</p>
            <p>数量：{{ product.quantity }}</p>
            <p>积分：{{ product.costPoints }} 积分</p>
          </div>
        </el-card>
      </el-space>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Refresh, Plus, Delete, Edit } from "@element-plus/icons-vue";
defineOptions({
  name: "Order",
  inheritAttrs: false,
});

import OrgAPI from "@/api/system/org";
import OrderAPI, { OrderPageVO, OrderForm, OrderPageQuery } from "@/api/system/order";
import { OrderStatusOptions } from "@/enums/OrderEnum.ts";
import { pcaTextArr } from "element-china-area-data";
import { useUserStore } from "@/store";

const userStore = useUserStore();
const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<OrderPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 订单管理表格数据
const pageData = ref<OrderPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  type: '',
  visible: false,
});

// 订单管理表单数据
const formData = reactive<OrderForm>({});

// 订单管理表单校验规则
const rules = reactive({
  courierId: [
    {
      required: true,
      message: "请选择配送人员",
      trigger: "change",
    },
  ]
});

/** 查询订单管理 */
function handleQuery() {
  loading.value = true;
  //判断当前登录用户角色
  if (userStore.judgeGuestUser()) {
    queryParams.username = userStore.userInfo.username;
  }
  if (userStore.judgeWorkerUser()) {
    queryParams.courierName = userStore.userInfo.username;
    let status = OrderStatusOptions.find(item => item.label == '已发货')?.value
    queryParams.status = [status]
  }
  OrderAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置订单管理查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

const courierOptions = ref()
/** 打开订单管理弹窗 */
async function handleOpenDialog(id?: number, type?: string) {
  dialog.visible = true;
  dialog.type = type

  courierOptions.value = await OrgAPI.getWorkersByOrgId(userStore.userInfo.orgId)

  if (id && type === "edit") {
    dialog.title = "修改订单管理";
    OrderAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else if (type === "add") {
    dialog.title = "新增订单管理";
  } else if (type === "deliver") {
    dialog.title = "发货";
    OrderAPI.getOrderFormForDeliver(id).then((data) => {
      Object.assign(formData, data);
    });
  }
}

/** 提交订单管理表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id && dialog.type == 'edit') {
        OrderAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else if (dialog.type == 'add') {
        OrderAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else if (dialog.type == 'deliver') {
        OrderAPI.shipments(formData)
          .then(() => {
            ElMessage.success("发货成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭订单管理弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除订单管理 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      OrderAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

/** 结算支付订单 */
function settleOrder(id: number) {
  loading.value = true;
  OrderAPI.settleOrder(id)
    .then(() => {
      ElMessage.success("支付成功");
      handleResetQuery();
    })
    .finally(() => (loading.value = false));
}

/**确认收货 */
function confirmReceipt(id: number) {
  loading.value = true;
  OrderAPI.confirmReceipt(id)
    .then(() => {
      ElMessage.success("确认收货成功");
      handleResetQuery();
    })
    .finally(() => (loading.value = false));
}

/**取消订单 */
function cancelOrder(id: number) {
  loading.value = true;
  OrderAPI.cancelOrder(id)
    .then(() => {
      ElMessage.success("取消订单成功");
      handleResetQuery();
    })
    .finally(() => (loading.value = false));
}

/**查看商品列表 */
const productDrawer = reactive({
  visible: false,
  title: '商品列表',
  productList: [] as any,
})
const viewProductDialog = (id: number) => {
  OrderAPI.viewProductList(id).then((data) => {
    productDrawer.productList = data;
    productDrawer.visible = true;
  })
}
const closeProductDrawer = () => {
  productDrawer.visible = false;
  productDrawer.productList = []
}
onMounted(() => {
  handleQuery();
});
</script>
<style scoped>
.dialog-footer {
  text-align: center;
}
</style>